"""
认证API路由
"""

from flask import Blueprint, request, jsonify
from flask_jwt_extended import create_access_token, create_refresh_token, jwt_required, get_jwt_identity
from app.models.user import User
from app import db
from app.utils.validators import validate_email, validate_password
from app.utils.decorators import validate_json

auth_bp = Blueprint('auth', __name__)


@auth_bp.route('/register', methods=['POST'])
@validate_json(['username', 'email', 'password'])
def register():
    """用户注册"""
    try:
        data = request.get_json()
        
        # 验证数据
        if not validate_email(data['email']):
            return jsonify({'error': '邮箱格式不正确'}), 400
        
        if not validate_password(data['password']):
            return jsonify({'error': '密码必须至少8位，包含字母和数字'}), 400
        
        # 检查用户是否已存在
        if User.find_by_username(data['username']):
            return jsonify({'error': '用户名已存在'}), 400
        
        if User.find_by_email(data['email']):
            return jsonify({'error': '邮箱已被注册'}), 400
        
        # 创建新用户
        user = User(
            username=data['username'],
            email=data['email'],
            first_name=data.get('first_name'),
            last_name=data.get('last_name')
        )
        user.set_password(data['password'])
        
        db.session.add(user)
        db.session.commit()
        
        # 生成令牌
        tokens = user.generate_tokens()
        
        return jsonify({
            'success': True,
            'message': '注册成功',
            'user': user.to_dict(),
            'tokens': tokens
        }), 201
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500


@auth_bp.route('/login', methods=['POST'])
@validate_json(['username', 'password'])
def login():
    """用户登录"""
    try:
        data = request.get_json()
        
        # 查找用户（支持用户名或邮箱登录）
        user = User.find_by_username(data['username'])
        if not user:
            user = User.find_by_email(data['username'])
        
        if not user or not user.check_password(data['password']):
            return jsonify({'error': '用户名或密码错误'}), 401
        
        if not user.is_active:
            return jsonify({'error': '账户已被禁用'}), 401
        
        # 更新最后登录时间
        user.update_last_login()
        
        # 生成令牌
        tokens = user.generate_tokens()
        
        return jsonify({
            'success': True,
            'message': '登录成功',
            'user': user.to_dict(),
            'tokens': tokens
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@auth_bp.route('/refresh', methods=['POST'])
@jwt_required(refresh=True)
def refresh():
    """刷新访问令牌"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user or not user.is_active:
            return jsonify({'error': '用户不存在或已被禁用'}), 401
        
        # 生成新的访问令牌
        access_token = create_access_token(identity=user.id)
        
        return jsonify({
            'success': True,
            'access_token': access_token
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@auth_bp.route('/me', methods=['GET'])
@jwt_required()
def get_current_user():
    """获取当前用户信息"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        return jsonify({
            'success': True,
            'user': user.to_dict()
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@auth_bp.route('/logout', methods=['POST'])
@jwt_required()
def logout():
    """用户登出"""
    try:
        # 在实际应用中，这里应该将令牌加入黑名单
        return jsonify({
            'success': True,
            'message': '登出成功'
        })
        
    except Exception as e:
        return jsonify({'error': str(e)}), 500


@auth_bp.route('/change-password', methods=['POST'])
@jwt_required()
@validate_json(['current_password', 'new_password'])
def change_password():
    """修改密码"""
    try:
        current_user_id = get_jwt_identity()
        user = User.query.get(current_user_id)
        
        if not user:
            return jsonify({'error': '用户不存在'}), 404
        
        data = request.get_json()
        
        # 验证当前密码
        if not user.check_password(data['current_password']):
            return jsonify({'error': '当前密码错误'}), 400
        
        # 验证新密码
        if not validate_password(data['new_password']):
            return jsonify({'error': '新密码必须至少8位，包含字母和数字'}), 400
        
        # 更新密码
        user.set_password(data['new_password'])
        db.session.commit()
        
        return jsonify({
            'success': True,
            'message': '密码修改成功'
        })
        
    except Exception as e:
        db.session.rollback()
        return jsonify({'error': str(e)}), 500
